﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;
using System.IO;

namespace Web.Account
{
    public partial class EditUser : System.Web.UI.Page
    {
        static string prevPage = String.Empty;
        static string defaultImage = "../UserImages/noavatar.png";
        static long UserID;
        static bool clickdelete = false;
        static USER user;
        static USER usersession;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack)
                return;
            if (Request.UrlReferrer != null)
            {
                prevPage = Request.UrlReferrer.ToString();
                hdntxtPrevPage.Value = prevPage;
            }
            usersession = (USER)Session["User"];
            if (usersession != null)
            {
                r = RoleService.GetRoleByID((long)usersession.ROLE_ID);
                if (((bool)usersession.IS_ADMIN) || ((bool)r.IS_MANAGER))
                 {
                     string requestEdit = Request.QueryString["id"];
                     if (requestEdit != null)
                     {
                         UserID = Convert.ToInt64(requestEdit);
                         user = UserService.GetUserByID(UserID);
                         LoadRole();
                         LoadDataUserEdit();
                         if (!(bool)usersession.IS_SUPER_USER)
                         {
                             divIsAdmin.Visible = false;
                         }

                     }
                 }
                 else
                 {
                     Response.Redirect("../Home.aspx");
                 }
            }
        }
        private void LoadDataUserEdit()
        {
            USER_DETAIL userDe = UserService.GetUserDetailByID(UserID);
            if (userDe != null)
            {
                //User Logiin & Role
                txtUsername.Text = userDe.USER_NAME;
                txtPrimaryMail.Text = userDe.PRIMARY_EMAIL;
                txtFirstName.Text = userDe.SUR_NAME;
                txtLastName.Text = userDe.NAME;
                chbIsAdmin.Checked = (bool)userDe.IS_ADMIN;
                chbIsActive.Checked = (bool)userDe.ACTIVE;
                RadComboBoxItem ass = ddlRole.FindItemByValue(userDe.ROLE_ID.ToString());
                if (ass != null)
                {
                    ddlRole.ClearSelection();
                    ass.Selected = true;
                }


                //More Information
                txtTitle.Text = userDe.TITLE;
                txtFax.Text = userDe.FAX;
                txtDepartment.Text = userDe.DEPARTMENT;
                txtOtherEmail.Text = userDe.OTHER_EMAIL;
                txtOfficePhone.Text = userDe.PHONE_OFFICE;
                txtCRMPhoneEx.Text = userDe.CRM_EXTENSION;
                txtMobilePhone.Text = userDe.PHONE_MOBILE;
                txtHomePhone.Text = userDe.PHONE_HOME;
                txtSecondaryPhone.Text = userDe.PHONE_SECONDARY;
                // chua load default lead view + report to

                //User Address
                txtStreetAddress.Text = userDe.ADDRESS_STREET;
                txtCountry.Text = userDe.ADDRESS_COUNTRY;
                txtCity.Text = userDe.ADDRESS_CITY;
                txtPostalCode.Text = userDe.ADDRESS_POSTALCODE;
                txtState.Text = userDe.ADDRESS_STATE;

                //User Photograph
                imgprw.Src = userDe.IMAGE;
                //Mail Options
            }
            else
            {
                divContent.Style["display"] = "none";
                divError.Style["display"] = "block";
            }
        }
        private void LoadRole()
        {
            ddlRole.DataSource = RoleService.GetRoles();
            ddlRole.DataBind();
            ddlRole.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }

        private int UpdateUser()
        {
            USER user = UserService.GetUserByID(UserID);
            //user.DELETED = false;
            user.CREATED_BY = 1;
            user.DATE_ENTERED = DateTime.Now;
            user.MODIFIED_USER_ID = 1;
            user.DATE_MODIFIED = user.DATE_ENTERED;
            user.PWD_LAST_CHANGED = user.DATE_ENTERED;
            //User login & role
            user.USER_NAME = txtUsername.Text;
            user.PRIMARY_EMAIL = txtPrimaryMail.Text;
            user.SUR_NAME = txtFirstName.Text;
            user.NAME = txtLastName.Text;

            user.ACTIVE = chbIsActive.Checked;
            user.IS_ADMIN = chbIsAdmin.Checked;
            if (ddlRole.SelectedValue != "-1")
            {
                user.ROLE_ID = Convert.ToInt64(ddlRole.SelectedValue);
            }
            else user.ROLE_ID = -1;

            //More information
            user.TITLE = txtTitle.Text;
            user.FAX = txtFax.Text;
            user.DEPARTMENT = txtDepartment.Text;
            user.OTHER_EMAIL = txtOtherEmail.Text;
            user.PHONE_OFFICE = txtOfficePhone.Text;

            user.PHONE_MOBILE = txtMobilePhone.Text;
            //user.REPORTS_TO_ID = 1;//check
            user.PHONE_HOME = txtHomePhone.Text;
            user.PHONE_SECONDARY = txtSecondaryPhone.Text;
            user.CRM_EXTENSION = txtCRMPhoneEx.Text;
            //User address
            user.ADDRESS_STREET = txtStreetAddress.Text;
            user.ADDRESS_COUNTRY = txtCountry.Text;
            user.ADDRESS_CITY = txtCity.Text;
            user.ADDRESS_POSTALCODE = txtPostalCode.Text;
            user.ADDRESS_STATE = txtState.Text;

            //Add new user
            string img = user.IMAGE;
            if (AsyncUpload1.UploadedFiles.Count > 0)
            {
                if (img != defaultImage)
                    System.IO.File.Delete(Server.MapPath(user.IMAGE));
                string filename = "~/ProductImages/" + DateTime.Now.ToString("ddMMyyhhmmssttfff") + AsyncUpload1.UploadedFiles[0].GetExtension();
                AsyncUpload1.UploadedFiles[0].SaveAs(Server.MapPath(filename));
                user.IMAGE = filename;
            }
            else
            {
                if ((clickdelete == true) && (img != defaultImage))
                {
                    System.IO.File.Delete(Server.MapPath(user.IMAGE));
                    user.IMAGE = defaultImage;
                }
            }

            return UserService.UpdateUser(user);
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int updateUser = UpdateUser();
            if (updateUser == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Update user successful !" + "','" + "Users.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Update user successful !", "Users.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not update user !" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Can not update user !", "");
        }

        protected void btn_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(prevPage);
        }
        protected void btn_Delete_ServerClick(object sender, EventArgs e)
        {
            USER user = UserService.GetUserByID(UserID);
            int UserDel = UserService.DeleteUser(UserID);
            if (UserDel == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Delete user successful !" + "','" + "Users.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Delete USER successful !", "Users.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete user !" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Can not delete user !", "");

        }

        protected void DeleteImage_Click(object sender, EventArgs e)
        {
            imgprw.Src = defaultImage;
            clickdelete = true;

        }
    }
}